{% import _self as self %}

<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />

<div class="content">

    <script>
        var year = parseInt("{{ server_time['year'] }}", 10);
        var month = parseInt("{{ server_time['month'] }}", 10) - 1;
        var day = parseInt("{{ server_time['day'] }}", 10);
        var hour = parseInt("{{ server_time['hour'] }}", 10);
        var minute = parseInt("{{ server_time['minute'] }}", 10);
        var second = parseInt("{{ server_time['second'] }}", 10);

        server_time = new Date(year, month, day, hour, minute, second);

        green = getComputedStyle(document.documentElement).getPropertyValue('--date-picker-green');
        yellow = getComputedStyle(document.documentElement).getPropertyValue('--date-picker-yellow');
        red = getComputedStyle(document.documentElement).getPropertyValue('--date-picker-red');
    </script>

    {% if userGroup == 1 %}
        <div style="float: right; margin-bottom: 20px;">
            {# button to open all of the subfolders and cookie it#}
            <a onclick='setCookie("foldersOpen",openAllDivForCourseMaterials());' class="btn btn-primary">Open/Close All Folders</a>
            {# button to set the release dates of all files in the page/course materials #}
            <a onclick='setFolderRelease("{{ folderPath }}","{{ fileReleaseDates[folderPath] }}","{{ id }}",
                    [{% for file in inDir %}
                        "{{ file }}",
                    {% endfor %}]
                    )' class="btn btn-primary">Set All Release Dates</a>
            <a onclick="newUploadCourseMaterialsForm()" class="btn btn-primary">Upload Course Materials</a>
        </div>
    {% endif %}
    <h1>Course Materials</h1>
    {% if userGroup==1 %}
        <ul style="justify-self: center" id="details-legend" class="table-bordered">
            <li>
                <i class="fas fa-circle grader-NULL"></i>
                Null date
            </li>
            <li>
                <i class="fas fa-circle grader-invalid"></i>
                Never release for at LEAST 10 years
            </li>
            <li>
                <i class="fas fa-circle grader-3"></i>
                Imminent release in at MOST 10 years
            </li>
            <li>
                <i class="fas fa-circle grader-1"></i>
                Released
            </li>
        </ul>
    {% endif %}
    <div class="inner-container" id="file-container">
        {{ self.display_files(self, submissions, fileShares, fileReleaseDates, "s", 0, "submissions", userGroup, uploadFolderPath, inDir, display_file_url, user_section, file_sections, hide_from_students) }}

    </div>
</div>

{% macro display_files(self, files, fileShares, fileReleaseDates, id, indent, title, userGroup, folderPath, inDir, display_file_url,user_section, file_sections, hide_from_students) %}
    {# Files on top #}
        {% for dir, path in files|filter((path,dir) => path is not iterable) %}
            {% if userGroup != 4 or fileShares[path] == "1" %}
                {{ self.display_file(self, dir, fileShares, fileReleaseDates, path, id ~ "f" ~ loop.index, indent, title, userGroup, inDir, display_file_url, user_section, file_sections, hide_from_students) }}
            {% endif %}
        {% endfor %}

        {# Directories underneath #}
        {% for dir, path in files if path is iterable %}
            {{ self.display_dir(self, dir, fileShares, fileReleaseDates, path, id ~ "d" ~ loop.index, indent, title, userGroup, folderPath ~ '/' ~ dir,inDir, display_file_url, user_section, file_sections, hide_from_students) }}
        {% endfor %}
{% endmacro %}


{% macro display_file(self, dir, fileShares, fileReleaseDates, path, id, indent, title, userGroup, inDir, display_file_url, user_section, file_sections, hide_from_students) %}
    {% set this_file_section = file_sections[path] %}
    {% set this_hide_from_students = hide_from_students[path] %}
    {% if userGroup != 4 or this_file_section is null or (this_hide_from_students == "off" and user_section in this_file_section)%}
    <div>
        <div class="file-viewer">

            <k class="fas fa-file" style='vertical-align:text-bottom;'></k>
            {{ dir }}&nbsp;
            {% set dirExtension = dir|split('.')|last|lower %}
            {% if '.' ~ dirExtension in ['.pdf', '.jpg', '.jpeg', '.c', '.cpp', '.s', '.twig', '.py', '.java', '.png', '.txt', '.h', '.html', '.php', '.js', '.sql', '.sh', '.md', '.csv', '.salsa', '.erl', '.oz', '.pl', '.hs', '.gif'] %}
                 <a target="_blank" href="{{ display_file_url }}?dir=course_materials&path={{ path | url_encode }}" aria-label="Pop up {{ dir }} in a new window"><i class="fas fa-window-restore" title="Pop up the file in a new window"></i></a>
            {% endif %}
            <a onclick='downloadFile("{{ path | url_encode }}", "course_materials")' aria-label="Download {{ dir }}"><i class="fas fa-download" title="Download the file"></i></a>
            {% if userGroup == 1 %}

               <a onclick='newDeleteCourseMaterialForm("{{ path | url_encode }}", "{{ dir }}");' aria-label="Delete {{ dir }}"> <i class="fas fa-trash" title="Delete the file" style="font-size: 16px; margin: 5px;"></i></a>
                <label for="latest-events">Share to student on</label>
                <input name="release_date" id="date_to_release_{{ id }}" class="date_picker" type="text" size="26"  value="{{ fileReleaseDates[path]}}"/>
                {% if not(this_file_section is null) %}
                    {% if this_hide_from_students == "on" %}
                        <label>Sections (Hidden):
                        {{this_file_section|join(',')}}
                        </label>
                    {% else %}
                        <label>Sections:
                        {{this_file_section|join(',')}}
                        </label>
                    {% endif %}

                {% endif %}
                <script>

                    function determineRelease(inputID){
                        var now = server_time;

                        function pad(str){
                            return ('0'+str).slice(-2);
                        }

                        var date = now.getFullYear()+'-'+pad(now.getMonth()+1)+'-'+pad(now.getDate());
                        var time = pad(now.getHours())+":"+pad(now.getMinutes())+":"+pad(now.getSeconds());
                        var currentDT = date+' '+time;
                        var neverDT = (now.getFullYear()+10)+'-'+pad(now.getMonth()+1)+'-'+pad(now.getDate())+' '+time;

                        //get the value in each file so the color can be assigned
                        //based on the time chosen
                        var inputDT = document.getElementById(inputID);
                        var fileDT = inputDT.value;
                        //also custom colors for this page for readability
                        if(new Date(fileDT).getTime()<=new Date(currentDT).getTime()){
                            return green;
                        }
                        else if(new Date(fileDT).getTime()>=new Date(neverDT).getTime()){
                            return red;
                        }
                        else{
                            return yellow;
                        }

                    }
                    document.getElementById('date_to_release_{{ id }}').style.backgroundColor= determineRelease('date_to_release_{{ id }}');

                    flatpickr("#date_to_release_{{ id }}",{
                    plugins: [ShortcutButtonsPlugin(
                        {
                            button: [
                                {
                                    label: "Now"
                                },
                                {
                                    label: "Tomorrow"
                                },
                                {
                                    label: "End of time"
                                }

                            ],
                            onClick: (index, fp) => {
                                let date;
                                switch (index) {
                                    case 0:
                                        updateToServerTime(fp);
                                        break;
                                    case 1:
                                        updateToTomorrowServerTime(fp);
                                        break;
                                    case 2:
                                        date = new Date("9998-01-01");
                                        fp.setDate(date,true);
                                        break;

                                }
                            }
                        }
                    )],
                    allowInput: true,
                    enableTime: true,
                    enableSeconds: true,
                    time_24hr: true,
                    dateFormat: "Y-m-d H:i:S",
                    onOpen: handleTimeZones('{{ core.getConfig().getTimezone().getName() }}'),
                    onClose: function() {
                                            setNewDateTime('date_to_release_{{ id }}', '{{ path }}');
                                            determineRelease('date_to_release_{{ id }}');
                                            changePermission('{{ path }}','1');
                                         }
                    });
                </script>
            {% endif %}
        </div>
        <div class="file-viewer-data" id="file_viewer_{{ id }}" style="margin-left:{{ indent * -15 }}px" data-file_name="{{ dir }}" data-file_url="{{ path }}"></div>
    </div>
    {% endif %}
{% endmacro %}

{% macro display_dir(self, dir, fileShares, fileReleaseDates, contents, id, indent, title, userGroup, folderPath,inDir, display_file_url, user_section, file_sections, hide_from_students) %}
    {% if indent == 0 %}
        {{ self.display_files(self, contents, fileShares, fileReleaseDates, id, indent + 1, title, userGroup, folderPath,inDir, display_file_url, user_section, file_sections, hide_from_students
        ) }}
    {% else %}
    <div>

        <div class="div-viewer">
            {# button to open each folder #}
            <a class='openAllDiv openAllDiv{{ title }} openable-element-{{ title }}' id='{{ dir }}' onclick='setCookie("{{ folderPath }}",openDivForCourseMaterials("{{ id }}")+"{{ id }}")'>
                <span class="fas fa-folder open-all-folder" style='vertical-align:text-top;font-size:20px'></span>
                {{ dir }}
            </a>
            <a onclick='downloadCourseMaterialZip("{{ dir }}", "{{ folderPath | url_encode }}")' aria-label="Download the folder: {{ dir }}"><i class="fas fa-download" title="Download the folder"></i></a>
            {% if userGroup == 1 %}
               <a onclick='newDeleteCourseMaterialForm("{{ folderPath | url_encode  }}", "{{ dir }}");' aria-label="Delete the folder: {{ dir }}"> <i class="fas fa-trash" title="Delete the folder" style="font-size: 16px; margin: 5px;"></i></a>
                {# button to choose release date for all files in folder and subfolders #}
                <a onclick='setFolderRelease("{{ folderPath }}","{{ fileReleaseDates[folderPath] }}","{{ id }}",
                [{% for file in inDir %}
                        {% if folderPath in file %}
                            "{{ file }}",
                        {% endif %}
                {% endfor %}]
                        )' class="btn btn-primary">Set Folder Release Date</a>
            {% endif %}
        </div>
        <div id='div_viewer_{{ id }}' style='margin-left:15px; display: none' data-file_name="{{ dir }}">

            {# Recurse #}

            {{ self.display_files(self, contents, fileShares, fileReleaseDates, id, indent + 1, title, userGroup, folderPath,inDir, display_file_url, user_section, file_sections, hide_from_students) }}

        </div>
    </div>
    {% endif %}
{% endmacro %}


<script type="text/javascript">
    //set cookie for open adapted from w3schools
    function setCookie(cName,cVal){
        document.cookie = cName+'='+cVal;
    }
    //get the value for the cookie with this name
    function getCookie(cName) {
        var name = cName+'=';
        var decodedCookie = decodeURIComponent(document.cookie);
        var ca = decodedCookie.split(';');
        for(var i = 0; i <ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') {
                c = c.substring(1);
            }
            if (c.indexOf(name) == 0) {
                return c.substring(name.length, c.length);
            }
        }
        return "";
    }
    window.onload = function () {
        //determine if folders have been left open or closed
        var folderCookie = getCookie('foldersOpen');
        //if the cookie says it is open
        if(folderCookie == "open"){
            //open all the folders
            openAllDivForCourseMaterials();
            //
            {% for file in inDir %}
                //if one of the subdirs, check if it is closed post opening all
                var subFolderCookie = getCookie("{{ file }}".substr(0,'{{ file }}'.lastIndexOf("/")));
                if(subFolderCookie.indexOf("closed")==0){
                    //if closed. close it after it has been opened by the override above
                    closeDivForCourseMaterials(subFolderCookie.substr(6,subFolderCookie.length));
                }
            {% endfor %}
        }
        else{
            //makes sure that opened folders don't get opened multiple times
            let trackOpens = new Map();
            //goes through all possible directories
            {% for file in inDir %}
                    //get the cookie for each dir
                    var subFolderCookie = getCookie("{{ file }}".substr(0,'{{ file }}'.lastIndexOf("/")));
                    //if the folder is open
                    if(subFolderCookie.indexOf("open")==0){
                        //check if the folder has been opened already (do it it again will close it)
                        if(trackOpens.get(subFolderCookie.substr(4,subFolderCookie.length)) === undefined){
                            //undefined means it has not been opened
                            //set the value as open so it will not be reopened
                            trackOpens.set(subFolderCookie.substr(4,subFolderCookie.length),"released");
                            //open the folder
                            openDivForCourseMaterials(subFolderCookie.substr(4,subFolderCookie.length));
                        }
                    }
                    else{
                        if(subFolderCookie.indexOf("closed")==0){
                            //if the folder should be closed, close it
                            closeDivForCourseMaterials(subFolderCookie.substr(6,subFolderCookie.length));
                            //there's no way to open it in that function
                        }
                    }
            {% endfor %}
        }
        // loop thru each div_viewer_xxx
        var jumpToScrollPosition = document.cookie.replace(/(?:(?:^|.*;\s*)jumpToScrollPosition\s*\=\s*([^;]*).*$)|^.*$/, "$1");
        if (jumpToScrollPosition.length > 0 && jumpToScrollPosition != '-1') {

            $('[id^=div_viewer_]').each(function() {
            var number = this.id.replace('div_viewer_', '').trim();
            var keyValuePairs = document.cookie.split(';');

            for(var i = 0; i < keyValuePairs.length; i++) {
                var name = keyValuePairs[i].substring(0, keyValuePairs[i].indexOf('=')).trim();
                var value = keyValuePairs[i].substring(keyValuePairs[i].indexOf('=')+1);
                if (name === 'cm_'+number && value === '1') {
                    openDivForCourseMaterials(number);
                    document.cookie = 'cm_' + number + '='; // clean up cookie since we don't need this anymore
                }
            }
        });
            // jump to last location if scroll is enabled.
            window.scrollTo(0, jumpToScrollPosition);
            document.cookie = 'jumpToScrollPosition=-1';

        }
        else {
            // clean up all cookies which are stated with "cm_";
            $('[id^=div_viewer_]').each(function() {
            var number = this.id.replace('div_viewer_', '').trim();
            var keyValuePairs = document.cookie.split(';');

            for(var i = 0; i < keyValuePairs.length; i++) {
                var name = keyValuePairs[i].substring(0, keyValuePairs[i].indexOf('=')).trim();
                if (name === 'cm_'+number) {
                    document.cookie = 'cm_' + number + '=';
                }
            }
        });
        }
    };

    function shareToOther(id, path) {
        // pass filename to server to record the permission of the file
        var idName = "#share_checkbox_" + id;
        if($(idName).is(':checked')) {
            changePermission(path, '1');
        }
        else {
            changePermission(path, '0');
        }
    }

</script>


{% include('course/SetFolderReleaseForm.twig') %}
{% include 'course/UploadCourseMaterialsForm.twig' with {reg_sections: reg_sections} %}
{% include('course/DeleteCourseMaterialForm.twig') %}
